package com.spzx.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.user.domain.vo.RegionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.RegionMapper;
import com.spzx.user.domain.Region;
import com.spzx.user.service.IRegionService;

/**
 * 地区信息Service业务层处理
 *
 * @author atguigu
 * @date 2024-09-29
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
    @Autowired
    private RegionMapper regionMapper;

    /**
     * 查询地区信息列表
     *
     * @param region 地区信息
     * @return 地区信息
     */
    @Override
    public List<Region> selectRegionList(Region region) {
        return regionMapper.selectRegionList(region);
    }

    @Override
    public List<RegionVO> treeSelect() {
        List<RegionVO> regionVOS = new ArrayList<>();

        //根据级别查询市
        List<Region> regions = regionMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getLevel, 1));

        regions.forEach(region -> {
            RegionVO regionVO = new RegionVO();
            BeanUtils.copyProperties(region, regionVO);
            List<RegionVO> regionVOSChilden = new ArrayList<>();
            //根据code查找市
            List<Region> regionss = regionMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, region.getCode()));
            regionss.forEach(region1 -> {

                RegionVO regionVO2 = new RegionVO();
                BeanUtils.copyProperties(region1, regionVO2);

                List<RegionVO> regionVOSChilden2 = new ArrayList<>();
                //根据市code 查找区


                List<Region> regions3 = regionMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, region1.getCode()));
                regions3.forEach(region2 -> {
                    RegionVO regionVO3 = new RegionVO();
                    BeanUtils.copyProperties(region2, regionVO3);
                    regionVOSChilden2.add(regionVO3);

                });

                regionVO2.setChildren(regionVOSChilden2);
                regionVOSChilden.add(regionVO2);


            });
            regionVO.setChildren(regionVOSChilden);
            regionVOS.add(regionVO);
        });


        return regionVOS;
    }

}
